package com.md.notes.model.module.socket;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetworkUtils {
    private static final String TAG = "NetworkUtils";
    public static final int REQUEST_CODE = 1001;
    private static final
    String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET
    };

    public static boolean checkPermissions(Activity activity) {
        for
        (String perm : REQUIRED_PERMISSIONS) {
            if
            (ActivityCompat.checkSelfPermission(activity, perm)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    public static void requestPermissions(Activity activity) {
        ActivityCompat.requestPermissions(
                activity,
                REQUIRED_PERMISSIONS,
                REQUEST_CODE
        );
    }
    
    /**
     * 获取设备当前的IP地址
     * @param context 上下文
     * @return IP地址字符串，如果无法获取则返回"未知"
     */
    public static String getDeviceIpAddress(Context context) {
        // 方法1：通过WifiManager获取
        /*String ipAddress = getWifiIpAddress(context);
        if (!"未知".equals(ipAddress)) {
            return ipAddress;
        }*/
        
        // 方法2：通过网络接口获取
        String ipAddress = getNetworkInterfaceIpAddress();
        if (!"未知".equals(ipAddress)) {
            return ipAddress;
        }
        
        // 如果都获取失败，返回未知
        return "未知";
    }
    
    /**
     * 通过WifiManager获取IP地址
     */
    private static String getWifiIpAddress(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null && wifiManager.isWifiEnabled()) {
                int ipInt = wifiManager.getConnectionInfo().getIpAddress();
                if (ipInt != 0) {
                    return Formatter.formatIpAddress(ipInt);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取Wifi IP地址失败", e);
        }
        return "未知";
    }
    
    /**
     * 通过网络接口获取IP地址
     */
    private static String getNetworkInterfaceIpAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                // 跳过回环接口、虚拟接口等
                if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual()) {
                    continue;
                }
                
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        String hostAddress = address.getHostAddress();
                        if (hostAddress != null && !hostAddress.equals("127.0.0.1")) {
                            return hostAddress;
                        }
                    }
                }
            }
        } catch (SocketException e) {
            Log.e(TAG, "获取网络接口IP地址失败", e);
        }
        return "未知";
    }
}

